#!/usr/bin/env python

#################################################################################
#
# Copyright (c) 2006 Michigan State University
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#################################################################################

#################################################################################
#
#	Author:
#		Nathan Collins <npcollins@gmail.com>
#
#################################################################################

# imports
from dbinter import *
from util import *
from oaicookie import *
from time import time
import cgi
from directory import *
from oaiemail import *
from auth import *
from approval import *

def handleSuggest(recID, ar, editor=''):
	db = oai_db()
	db.connect()
		
	# send email if address present
	sub = db.query_dict('SELECT * FROM directorySubmissions WHERE recID = %s;' % recID)
	
	if len(sub) < 1:
		return alreadyDone()

	sub = sub[0]

	email = sub['optionalEmail']

	# if delete requested, then remove recHash from directory
	if ar == 'd':
		oldHash = sub['recHash']
		# retrieve the parentHash of the soon to be deleted record
		result = db.query_dict("SELECT * FROM directoryTree WHERE recHash = '%s';" % oldHash)
		grandParentHash = result[0]['parentHash']

		# update all entries that have oldHash for parentHash to be grandParentHash
		db.query("UPDATE directoryTree SET parentHash = '%s' WHERE parentHash = '%s';" % (grandParentHash, oldHash) )

		# remove directory entry
		db.query('DELETE FROM directoryTree WHERE recHash = \'%s\';' % oldHash)

		# remove suggestion
		db.query('DELETE FROM directorySubmissions WHERE recID = %s;' % recID)
		
		return '<b>Directory Entry Deleted</b>'
		suggestModified(email)

	# if rejected, delete suggestion
	elif ar == 'r':
		db.query('DELETE FROM directorySubmissions WHERE recID = %s;' % recID)
		
		# rejection string
		return '<b>Rejected</b>'
		suggestRejected(email)

	# if approved, add to directoryTree and remove from submissions
	elif ar == 'a':
		modify = sub['isModify']
		del sub['optionalEmail']
		del sub['recID']
		del sub['isModify']
		sub['editorApproved'] = editor
		
		# modify entry - remove original
		if modify == 'Y':
			oldHash = sub['recHash']
			# recalculate recHash based on title for non-records
			if sub['isRecord'] == 'N': sub['recHash'] = directoryHash(sub['parentHash'],sub['entryTitle'])
			# remove old record
			db.query('DELETE FROM directoryTree WHERE recHash = \'%s\';' % oldHash)
			# update all record whose parentHash was oldHash to be the recalc hash
			db.query("UPDATE directoryTree SET parentHash = '%s' WHERE parentHash = '%s';" % (sub['recHash'], oldHash) )
			
			# update all record whose targetHash was oldHash to be the recalc hash
			db.query("UPDATE directoryTree SET targetHash = '%s' WHERE targetHash = '%s';" % (sub['recHash'], oldHash) )

		try:
			# we want to catch exceptions here rather than in db module
			db.setsilent(1)
			db.insert('directoryTree',sub)
			db.setsilent(0)
		except:
			failed = '<b>COULD NOT APPROVE:</b> '
			if sub['isRecord'] == 'Y':
				failed += 'Please check that this record is not already in the directory.'
			else:
				failed += 'Please check that a directory/link with this title does not already exist.'
			return failed

		db.query('DELETE FROM directorySubmissions WHERE recID = %s;' % recID)

		# approved string
		return '<b>Approved</b>'
		suggestApproved(email)

	db.disconnect()

class editor:
	"""
	The editor class handles the output of the editor page.
	"""
	def __init__(self):
		self.params = {}
		self.loginSuccess = 0
		self.loginMessage = ''
		self.loginHandler()
	
	def loginHandler(self):
		"""
		Authenticate and handle logins.
		"""
		self.loginSuccess, self.loginMessage = authenticate()
		# if failed, clear sessionid
		if self.loginSuccess != 1: setCookieVars({'sid':''})

	def process(self):
		# pull cgi
		self.params = cgi.FieldStorage()
		try:
			self.editorAction = self.params['a'].value
		except: 
			self.editorAction = ''

		# make the page

		if self.editorAction == 'logout':
			# log out - delete cookie sid
			setCookieVars({'sid':''})
			self.loginSuccess = 0

		# print header
		print "Content-type: text/html\n\n"
		outbit('pg_header_4')

		outbit('pg_title_1')

		outbit('pg_bar_short')

		print '<div align="center" class="margin2em">'
		print '<b>EDITOR\'S PAGE</b><br><br>'

		# authenticate session
		if self.loginSuccess == 1:
			self.actions()
		else:
			print '<b>%s</b>' % self.loginMessage
			self.login()
		
		print '</div>'
		
		# print footer
		outbit('pg_footer_3')

	def actions(self):
		"""
		Print out the editor actions and page.
		"""
		# pring actions header
		outbit('pg_editor_actions_1')

		if self.editorAction == 'apprv':
			# print approve page
			self.approve()

		elif self.editorAction == 'admin':
			# print admin page
			self.administer()

		elif self.editorAction == 'pwchg':
			# print password change page
			self.pwchange()

		else:
			# print nothing
			pass

	def login(self):
		"""
		Print out login form.
		"""
		outbit('pg_editor_login_1')

	def pwchange(self):
		"""
		Print out the password change form for the current editor.
		"""
		try:
			# pull change info
			npw = cui(self.params['npw'].value)
			# no empty pws
			if len(npw) < 1: raise

			sid = cui(getCookieVar('sid'))

			quick_noret("UPDATE directoryLogins SET loginPassword = '%s' WHERE sessionID = '%s';" % (npw,sid) )

			print '<b>Password changed successfully.</b>'
		except:
			print '<b>Enter new password twice.</b>'
		
		outbit('pg_editor_pwchange_1')

	def approve(self):
		"""
		Print out submissions needing approval/deletion with options to view/approve.
		"""
		db = oai_db()
		db.connect()

		# query for records
		submissions = db.query_dict("SELECT * FROM directorySubmissions;")
		print '<div class="results"><br><br>'

		for submis in submissions:
			divNum = submis['recID']
			modify = submis['isModify']
			print '<div class="resultShad">'
			print '<div id="submis%s" class="l_align resultItem">' % (divNum)
			if modify == 'N':
				# print out new submission
				outSubmission(divNum, submis)
			else:
				# print out modification
				outModify(divNum, submis)
			print '</div></div><br>'

		# if there were no submissions
		if len(submissions) < 1:
			print '<b>There are no pending submissions to the directory.</b><br><br>'

		print '<a href="editor.py?a=apprv">Refresh page to check for new submissions</a>'
		print '</div>'
		db.disconnect()

	def administer(self):
		"""
		Print out the administration page for handling editor accounts.
		"""
		# verify super editor
		sid = cui(getCookieVar('sid'))
		superLookup = quick_query('SELECT superEditor FROM directoryLogins WHERE sessionID = \'%s\';' % sid)

		if len(superLookup) < 1 or superLookup[0]['superEditor'] != 'Y':
			print '<b>You are not a super editor and can not administer other editors.</b>'
			return

		# otherwise, user is a super editor
		def pullAction(actn):
			try:
				return cui(self.params[actn].value)
			except: return None

		# pull actions and modify db
		acct = pullAction('acct')
		if acct != None:
			# enable/disable acct
			active = pullAction('active')
			if active == 'Y':
				quick_noret("UPDATE directoryLogins SET enableAccount = 'Y' WHERE loginName = '%s';" % acct)
			elif active == 'N':
				quick_noret("UPDATE directoryLogins SET enableAccount = 'N' WHERE loginName = '%s';" % acct)
				
				
			# enable/disable super editor
			super = pullAction('super')
			if super == 'Y':
				quick_noret("UPDATE directoryLogins SET superEditor = 'Y' WHERE loginName = '%s';" % acct)
			elif super == 'N':
				quick_noret("UPDATE directoryLogins SET superEditor = 'N' WHERE loginName = '%s';" % acct)

			# modify login name
			modn = pullAction('modn')
			if modn != None and len(modn.strip()) > 0:
				quick_noret("UPDATE directoryLogins SET loginName = '%s' WHERE loginName = '%s';" % (modn,acct))

			# modify password
			modp = pullAction('modp')
			if modp != None and len(modp) > 0:
				quick_noret("UPDATE directoryLogins SET loginPassword = '%s' WHERE loginName = '%s';" % (modp,acct))

			# delete acct
			delete = pullAction('delete')
			if delete == 'Y':
				quick_noret("DELETE FROM directoryLogins WHERE loginName = \'%s\';" % acct)

		# add new account?
		newEd = pullAction('ael')
		newEdPw = pullAction('aep')
		if newEd != None and newEdPw != None and len(newEd.strip()) > 0:
			# ok to add new editor
			quick_noret("INSERT IGNORE INTO directoryLogins (loginName, loginPassword) VALUES ('%s','%s');" % (newEd, newEdPw))

		# print admin page
		print '<b>Existing Accounts</b>'
		# function to change Y to N and ...
		def swapYN(yn):
			if yn == 'Y': return 'N'
			if yn == 'N': return 'Y'

		def outEditorAdmin(editor):
			# print a line of editor actions
			baseurl = '/editor.py?a=admin'
			print '<tr><td class="lt"> %s </td>' % editor['loginName']
			# active account
			print '<td class="ct"><a href="%s&acct=%s&active=%s">%s</a></td>' % (baseurl,editor['loginName'],swapYN(editor['enableAccount']),editor['enableAccount'])
			# super account
			print '<td class="ct"><a href="%s&acct=%s&super=%s">%s</a></td>' % (baseurl,editor['loginName'],swapYN(editor['superEditor']),editor['superEditor'])
			# change login
			print """
			<td class="ct">
			<form id="clg%s" action="" method="GET" onSubmit="return changeName('%s');">
			<input type="text" name="modn" value="" size="12" maxLength="30">
			<input type="submit" value="Change">
			</form></td>
			""" % (editor['loginName'],editor['loginName'])
			# change password
			print """
			<td class="ct">
			<form id="cpw%s" action="" method="GET" onSubmit="return changePw('%s');">
			<input type="text" name="modp" value="" size="12" maxLength="30">
			<input type="submit" value="Change">
			</form></td>
			""" % (editor['loginName'],editor['loginName'])
			# delete account
			print '<td class="ct"><a href="%s&acct=%s&delete=Y" onClick="return confirmDeleteAcct(\'%s\');">X</a></td>' % (baseurl,editor['loginName'],editor['loginName'])

		logins = quick_query('SELECT * FROM directoryLogins;')

		print '<table width=100%%>'
		print """<tr>	<td class="lt"><b>Login</b></td>
				<td class="ct"><b>Active</b></td>
				<td class="ct"><b>Super</b></td>
				<td class="ct"><b>Change Login</b></td>
				<td class="ct"><b>Change Password</b></td>
				<td class="ct"><b>Remove Account</b></td></tr>"""
		for ed in logins:
			outEditorAdmin(ed)
		print '</table>'

		# print out form to add new editor

		outbit('pg_editor_adduser_1')


#eof

